from flask import jsonify, current_app, render_template, session, g, request

from info import constants, db
from info.models import News, Category, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import newsdetail_bp


@newsdetail_bp.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
   # user_id = session.get("user_id")
   #
   # user = None
   #
   # if user_id:
   #
   #    try:
   #       user = User.query.get(user_id)
   #    except Exception as e:
   #       current_app.logger.error(e)
   #       return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")

    user = g.user

    # 查询新闻点击数据
    try:
      news_clicks_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
      current_app.logger.error(e)
      return jsonify(errno=RET.DBERR, errmsg="查询异常")

    news_rank_dict = []

    for news_obj in news_clicks_list if news_clicks_list else []:

      news_obj_dict = news_obj.to_dict()

      news_rank_dict.append(news_obj_dict)

    # 查询分类列表
    try:
      categoris_list = Category.query.all()
    except Exception as e:
      current_app.logger.error(e)
      return jsonify(errno=RET.DBERR, errmsg="查询分类列表异常")

    # 分类列表对象转换成字典列表
    categoris_list_dict = []
    for categories in categoris_list if categoris_list else []:
      categories_dict = categories.to_dict()
      categoris_list_dict.append(categories_dict)

    # 查询新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻对象查询异常")

    # to_dict: 将用户对象转化成字典
    data = {
        "user_info": user.to_dict() if user else None,
        "news_rank_list": news_rank_dict,
        "categoris_list_dict": categoris_list_dict,
        "news": news.to_dict() if news else None
    }

    return render_template("news/detail.html", data=data)


@newsdetail_bp.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():

    # 参数获取: news_id, user, action
    user = g.user

    if not user:
        current_app.logger.error("用户未登陆")
        return jsonify(errno=RET.USERERR, errmsg="用户未登陆")

    param_dict = request.json
    news_id = param_dict.get("news_id")
    action = param_dict.get("action")

    # 参数校验
    if not all([news_id, action]):

        current_app.logger.error("参数不足")
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if action not in ("collect", "cancel_collect"):

        current_app.logger.error("参数错误")
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not news_id:
        current_app.logger.error("参数错误")
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")


    # 逻辑处理
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询异常")

    if not news:
        current_app.logger.error("查询新闻对象异常")
        return jsonify(errno=RET.PARAMERR, errmsg="查询新闻对象异常")

    if action == "collect":

        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据异常")

    # 返回值
    return jsonify(errno=RET.OK,errmsg="OK")


